import _ from 'lodash';
import fp from 'lodash/fp';

/**
 * 数组提升维度
 *
 * @param {*} arr [1,2,3,5,6,7]
 * @returns [[1,2,3],[5,6,7]]
 */
const ascendingDimension = oneDimensionArray => {
  const { length } = oneDimensionArray;
  const splitIndexArray = [0]; // 待分割下标
  for (let i = 1; i < length; i += 1) {
    const current = oneDimensionArray[i];
    const prev = oneDimensionArray[i - 1];
    if (current - prev > 1) {
      splitIndexArray.push(i);
    }
  }
  splitIndexArray.push(length);
  const dist = [];
  const splitLength = splitIndexArray.length;
  for (let i = 1; i < splitLength; i += 1) {
    const indexArray = [
      oneDimensionArray[splitIndexArray[i - 1]],
      oneDimensionArray[splitIndexArray[i] - 1],
    ];
    dist.push(indexArray);
  }
  return dist;
};

const wrapOneDimension = arr => [arr];

/**
 * 将页码分割为二维数组保存
 *
 * @param {*} str '2-5-8,7-3-1,'
 */
const converStrToArray = str => {
  const result = str
    .split(',')
    .filter(item => item !== '')
    .map(range => {
      const fn = _.flowRight(
        array => array.sort((a, b) => a - b), // [7,3,1] 排序为 [1,3,7]
        fp.map(item => item - 1), // 将页码号 1 转化为索引号 0
        fp.map(item => parseInt(item, 10)), // ['2', '5', '8'] 转换为 [2, 5, 8]
        fp.split('-'), // 2-5-8 切割为 ['2', '5', '8']
      );
      return fn(range);
    });
  return result;
};

/**
 * 将二维数组拍平为不重复的一维数组
 *
 * @param {*} arr 二维数组 [[1, 3], [2, 4]]
 * @returns [1, 2, 3, 4]
 */
const flatDoubleDimensionalArray = arr =>
  // acc: [1, 2, 3, 4], currentRange: [1, 4]
  arr.reduce((acc, range) => {
    const { length } = range;
    for (let i = range[0]; i <= range[length - 1]; i += 1) {
      if (!acc.some(num => num === i)) {
        acc.push(i);
      }
    }
    return acc;
  }, []);

/**
 * 数组截短
 *
 * @param {*} arr 一维数组 [1, 4, 7]
 * @returns [1, 7]
 */
const shortArray = arr => {
  const { length } = arr;
  return [arr[0], arr[length - 1]];
};

/**
 * 将字符串转换成升序的一维数组
 */
const convert = _.flowRight(
  arr => arr.sort((a, b) => a - b),
  flatDoubleDimensionalArray,
  converStrToArray,
);
const fnSpliteMode = _.flowRight(
  fp.map(oneDimensionalArray => shortArray(oneDimensionalArray)),
  converStrToArray,
);
const fnNormalMode = _.flowRight(ascendingDimension, convert);
const fnOdd = _.flowRight(
  wrapOneDimension,
  arr => arr.filter(num => num % 2 === 0),
  convert,
);
const fnEven = _.flowRight(
  wrapOneDimension,
  arr => arr.filter(num => num % 2 === 1),
  convert,
);
const fnEachMode = _.flowRight(
  fp.map(item => [item]),
  arr => arr.sort((a, b) => a - b),
  flatDoubleDimensionalArray,
  converStrToArray,
);

export { fnSpliteMode, fnOdd, fnEven, fnNormalMode, fnEachMode };
